package com.bio.action;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

public interface Dispatcher {
	
	public String dispatch(String result);
	
	public Dispatcher MULTFORMAT = new MultformatDispatcher();
	
	static class MultformatDispatcher implements Dispatcher {
		
		private final static String DEFAULT_FORMAT = "html";
		
		private final static Map<String, String> ACCEPT_CONTENTS = new HashMap<String, String>() {{
			put("text/json", "json");
			put("text/xml", "xml");		
		}};
		
		private MultformatDispatcher() {}
		
		public String dispatch(String result) {
			HttpServletRequest request = ServletActionContext.getRequest();
			String accept = "text/html";
			
			if (request != null && request.getHeader("Accept") != null) {
			    accept = request.getHeader("Accept").toLowerCase();
			}
			
			String format = ACCEPT_CONTENTS.get(accept);
			if (format == null) {
				format = DEFAULT_FORMAT;
			}
			
			return result + "." + format;
		}
	};
}
